package c03.thread.api.join;

import util.Sleeper;
import lombok.extern.slf4j.Slf4j;

/**
 * 多线程下，调用了join方法的线程会被同步阻塞，其他线程不会被阻塞
 */
@Slf4j(topic = "c.JoinAndSleepTest2")
public class JoinAndSleepTest2 {
    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("********** t1 start **********");
            Sleeper.sleep(1);
            r1 = 10;
            log.debug("********** t1 end **********");
        }, "t1");

        Thread t2 = new Thread(() -> {
            log.debug("---------- t2 start ----------");
            Sleeper.sleep(2);
            r2 = 20;
            log.debug("---------- t2 end ----------");
        }, "t2");

        t1.start();
        t2.start();
        long start = System.currentTimeMillis();
        t2.join(); // 在main方法中执行执行t2.join()，只会同步阻塞main线程，并不会阻塞t1线程
        log.debug("t2 join");
        t1.join();
        log.debug("t1 join");
        long end = System.currentTimeMillis();
        log.debug("r1: {} r2: {} cost: {}", r1, r2, end - start);
    }
}